package com.woniuxy.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.entity.*;
import com.woniuxy.entity.dto.DrugDistributionDTO;
import com.woniuxy.mapper.DrugDistributionMapper;
import com.woniuxy.mapper.DrugMapper;
import com.woniuxy.producer.DelayExchangeProducer;
import com.woniuxy.service.IDoctorService;
import com.woniuxy.service.IDrugDistributionService;
import com.woniuxy.service.SaasService;
import com.woniuxy.util.*;
import lombok.Builder;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author：xurice
 * @date：Created in 2024/4/16 15:30
 * @description：
 * @modified By：
 * @version: $
 */
@Service
public class DrugDistributionServiceImpl implements IDrugDistributionService, SaasService {
    @Autowired
    DrugDistributionMapper drugDistributionMapper;

    @Autowired
    IDoctorService doctorService;

    @Autowired
    DrugMapper drugMapper;

    @Autowired
    private DelayExchangeProducer delayExchangeProducer;

    @Transactional(rollbackFor = RuntimeException.class)
    @SneakyThrows
    @Override
    public ResponseData<?> addDrugDistribution(DrugDistributionDTO drugDistributionDTO) {
        //添加用药明细表
        DrugDistribution drugDistribution = new DrugDistribution();
        drugDistribution.setPpCaseId(drugDistributionDTO.getPpCaseId());
        drugDistribution.setPpWorkerId(drugDistributionDTO.getPpWorkerId());
        //雪花id
        SnowflakeIdGenerator snow = new SnowflakeIdGenerator();
        long nextId = snow.nextId();
        drugDistribution.setPpNo(String.valueOf(nextId));
        //开单医生类型
        Doctor doctor = (Doctor) doctorService.queryDoctor().getData();
        if (doctor.getDocPtId().equals(CONSTANT.IS_OUTPATIENT)) {
            drugDistribution.setPpType("0");//门诊医生 开药 0
        }else {
            drugDistribution.setPpType("1");//住院医生 开药 1
        }
        drugDistributionMapper.addDrugDistribution(drugDistribution);

        delayExchangeProducer.send(JSON.toJSONString(drugDistributionDTO),"",0);

        List<DrugDetail> drugDetails = drugDistributionDTO.getDrugDetails();
        List<Integer> ids = new ArrayList<>();
        for (DrugDetail drugDetail : drugDetails) {
            ids.add(drugDetail.getMdDrugstoreId());
        }

        List<DrugDetail> drugDetailsNew = new ArrayList<>();
        List<Drug> drugs= drugMapper.queryByIds(ids);
        for (Drug drug : drugs) {
            for (DrugDetail drugDetail : drugDetails) {
                //购买数量大于库存
                if(drugDetail.getMdNum()>Integer.valueOf(drug.getDsStock())){
                    return new ResponseData<>().fail(ResponseEnum.DRUGSTOCK_NOT_ENOUGH);
                }
                if(drugDetail.getMdDrugstoreId().equals(drug.getId())){
                    drugDetail.setMdBuyPrice(drug.getDsOutPrice());
                    drugDetailsNew.add(drugDetail);
                    //计算药品库存
                    drug.setDsStock(String.valueOf(Integer.valueOf(drug.getDsStock())-drugDetail.getMdNum()));
                }
            }
        }
        //用药详情 设置 开药表的雪花id
        drugDetailsNew.forEach(e->e.setMdPrescriptionId(drugDistribution.getPpNo()));
        drugDistributionMapper.addBatchDrugDetails(drugDetailsNew);

        //添加开药费用明细表 t_mf
        DrugFund drugFund = new DrugFund();
        long mfNo = snow.nextId();
        drugFund.setMfNo(String.valueOf(mfNo));
        drugFund.setMfCaseId(drugDistributionDTO.getPpCaseId());
        drugFund.setMfMedicationId(String.valueOf(nextId));
        drugDistributionMapper.addDrugFund(drugFund);

        //减库存 批量 todo
        drugMapper.updateBatchStock(drugs);
        return new ResponseData<>().ok();
    }

    //分页加条件查询
    @Override
    public ResponseData<?> queryDrugDistribution(PageParam<DrugDistribution> pageParam) {
        PageHelper.startPage(pageParam.getPageNum(),pageParam.getPageSize());
        List<DrugDistribution> drugDistributionList = drugDistributionMapper.queryList(pageParam.getParam());
        return new ResponseData<>().ok(new PageInfo<>(drugDistributionList));
    }


    //查询开药详情
    @Override
    public ResponseData<?> queryDrugDetail(String ppNo) {
        DrugDetail drugDetail = new DrugDetail();
        drugDetail.setMdPrescriptionId(ppNo);
        List<DrugDetail> drugDetailList = drugDistributionMapper.queryDrugDetail(drugDetail);
        return new ResponseData<>().ok(drugDetailList);
    }


    @Override
    public ResponseData<?> updateDrugDistribution(Integer id) {
        DrugDistribution drugDistribution = drugDistributionMapper.queryDrugDistribution(id);
        //如果病人是门诊病人 而且没有缴费 返回错误信息
        if (drugDistribution.getPpType().equals("0")){
            if (drugDistribution.getPpStatus().equals("0")){
                return new ResponseData<>().fail(ResponseEnum.EMPTY);
            }
        }
        drugDistribution.setPpStatus("2");
        drugDistributionMapper.updateDrugStatus(drugDistribution);
        return new ResponseData<>().ok();

    }

    @Override
    public ResponseData<?> queryMDSByPpNo(Integer id) {
        if (id==null){
            return new ResponseData<>().fail(ResponseEnum.EMPTY);
        }
        List<String> stringList = drugDistributionMapper.queryPPNO(id);
        if (stringList.isEmpty()){
            return new ResponseData<>().fail(ResponseEnum.EMPTY);
        }
        List<DrugDetail> drugDetails = drugDistributionMapper.queryMDSByPpNo(stringList);
        return new ResponseData<>().ok(drugDetails);
    }
}
